<?php
require("dbFunctions.php");

/**
 * Given the QR Code of a resource that is currently checked out, set the
 * ID of the Supplier checking it in, set the checkin time and set has
 * been checked in to true.
 * 
 * Author: Steve Gennaoui
 * Date: 11/23/2012
 */

$qr_code = $_REQUEST['qr_code'];
$supplier_email = $_REQUEST['email'];
$supplier_id = getIDByEmail($supplier_email,"Suppliers");

if( is_null($qr_code) )
	die("No QR Code provided.");
if( is_null($supplier_email) )
	die("No Supplier email provided.");
if( !idIsValid($qr_code,"QR_Code") )
	die("QR Code is invalid.");
if( $supplier_id < 0 )
	die("Supplier email provided was not found. Either the email does not exist or the account has been de-activated for that email.");
if( !isCurrentlyCheckedOut($qr_code) )
	die("Resource with the provided QR Code is not currently checked out.");
if( !isTopLevel($qr_code) && isPartOfPackage($qr_code) )
	die("Resource is part of package. Top level item: \n".containerDetailsForResourceInPackage($qr_code)."\n This resource was not checked in.");

//Get the current time
$current_time = date("Y-m-d H:i:s");	//Gives the current datetime

//Get the row IDs for all the resource designations to be edited
// every resource in the package
$dbh = connectDB();
$query = "SELECT * FROM Resource_Designation WHERE (qr_code IN (SELECT contained_qr_code FROM Resource_Packages WHERE container_qr_code=:qr) ".
													"OR qr_code=:qr) AND has_been_checked_in=0";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':qr',$qr_code);
$stmt->execute();

$checkout_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach($checkout_rows as $checkout)
{
	$rd_id = $checkout['rd_id'];

	$query = "UPDATE Resource_Designation SET supplier_id_checkin=:sup_id, checkin_time=:ci_time, has_been_checked_in=1 WHERE rd_id=:rd_id";
	$stmt = $dbh->prepare($query);
	$stmt->bindParam(':sup_id', $supplier_id);
	$stmt->bindParam(':ci_time', $current_time);
	$stmt->bindParam(':rd_id', $rd_id);
	$stmt->execute();
}

$dbh = null;
$stmt = null;
?>
